package demo;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hp
 * Date: 2025-03-31
 * Time: 22:07
 */
public class ConsumerDemo {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1.建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("1.95.194.117");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("wangkun");
        connectionFactory.setPassword("200411");
        connectionFactory.setVirtualHost("study");
        Connection connection = connectionFactory.newConnection();

        //2.通信
        Channel channel = connection.createChannel();

        //3.声明队列(可以省略)
        channel.queueDeclare("hello",true,false,false,null);

        //4.消费消息
        /**
         *String basicConsume(String queue, boolean autoAck, Consumer callback)
         * queue: 队列名称
         * autoAck: 是否自动确认
         * callback: 接受消息后，执行的逻辑
         */
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            //从队列中收到消息, 就会执行的方法
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                /**
                 * consumerTag: 消费者标签, 通常是消费者在订阅队列时指定的。
                 * envelope: 包含消息的封包信息, 如队列名称，交换机等。
                 * properties: 一些配置信息
                 * body: 消息的具体内容
                 */

                System.out.println("接收到消息: " + new String(body));
            }
        };
        channel.basicConsume("hello",true,consumer);

        Thread.sleep(2000);
        //5.资源关闭
        channel.close();
        connection.close();
    }
}
